package com.sl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sl.entity.PageResult;
import com.sl.entity.Result;
import com.sl.entity.StatusCode;
import com.sl.pojo.Role;
import com.sl.service.RoleRouteService;
import com.sl.service.RoleService;
import com.sl.service.UserService;
import com.sl.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.sl.pojo.User;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 用户名验证
     */
    public static boolean checkName(String name) {
        String regExp = "^[^0-9][\\w_]{5,9}$";
        if(name.matches(regExp)) {
            return true;
        }else {
            return false;
        }
    }
    /**
     * 密码验证
     */
    public static boolean checkPwd(String pwd) {
        String regExp = "^[\\w_]{6,20}$";
        if(pwd.matches(regExp)) {
            return true;
        }
        return false;
    }
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 4.0查询：所有员工。在职，离职
     * @return
     */
    // @RequiresPermissions("user:all")
    @PostMapping("/all")
    public Result findAll(@RequestBody String data){
        log.info("查询所有员工:::在职and离职");
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer page = jsonObject.getInteger("page");
        if (null ==page) {page=1;}
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (null ==pageSize) {pageSize = 10;}
        PageHelper.startPage(page,pageSize);
        List<User> all = userService.findAll();
        List<UserVO> userVOList=new ArrayList<>();
        for (User user : all) {
            UserVO userVO = user2vo(user);
            userVOList.add(userVO);
        }
      /*  //保证ssionID一致。HttpServletRequest request
      Subject currentUser = SecurityUtils.getSubject();
        boolean authenticated = currentUser.isAuthenticated();
        log.info("登陆状态>>>" + authenticated);
        String sessionId = request.getSession().getId();
        log.info("sessionId:" + sessionId);*/
        PageResult<UserVO> userVOPageResult = new PageResult<>((long) userVOList.size(), userVOList);
        return new Result(true, StatusCode.OK,"查询所有历史员工成功",userVOPageResult);
    }

    /**
     * 4.1查询：在职员工
     */
    // @RequiresPermissions("user:on")
    @PostMapping("/on")
    public Result findOnJob(@RequestBody String data){
        log.info("查询所有员工:::在职");
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer page = jsonObject.getInteger("page");
        if (null ==page) {page=1;}
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (null ==pageSize) {pageSize = 10;}
        Map map=new HashMap();
        map.put("deleted",0);
        List<User> all = userService.findList(map,page,pageSize);
        //HttpServletRequest request
      /*  String sessionId = request.getSession().getId();
        log.info("sessionId>>>>" + sessionId);*/

        List<UserVO> userVOList=new ArrayList<>();
        for (User user : all) {
            UserVO userVO = user2vo(user);
            userVOList.add(userVO);
        }
        PageResult<UserVO> userVOPageResult = new PageResult<>((long) userVOList.size(), userVOList);
        return new Result(true, StatusCode.OK,"查询在职员工成功",userVOPageResult);
    }

    /**
     * 4.2查询：离职员工
     * @return
     */
    //@RequiresPermissions("user:leave")
    @PostMapping("/leave")
    public Result findLeaceJob(@RequestBody String data){
        log.info("查询所有员工:::离职");
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer page = jsonObject.getInteger("page");
        if (null ==page) {page=1;}
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (null ==pageSize) {pageSize = 10;}
        Map map=new HashMap();
        map.put("deleted",1);
        List<User> all = userService.findList(map,page,pageSize);
        List<UserVO> userVOList=new ArrayList<>();
        for (User user : all) {
            UserVO userVO = user2vo(user);
            userVOList.add(userVO);
        }
        PageResult<UserVO> userVOPageResult = new PageResult<>((long) userVOList.size(), userVOList);
        return new Result(true, StatusCode.OK,"查询离职员工成功",userVOPageResult);
    }

    /**注册》》用户名：必须是6-10位字母、数字、下划线，不能以数字开头》》密码:必须是6-20位的字母、数字、下划线
     * 1添加员工
     * @param data
     * @return
     */
    // @RequiresPermissions("user:add")
    @PostMapping("/add")
    public Result add(@RequestBody String data){
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        log.info("添加人员");

        User user = JSON.parseObject(data, User.class);
        String username = user.getUsername();
        String password = user.getPassword();
        while(!checkName(username)) {
            throw new RuntimeException("用户名：必须是6-10位字母、数字、下划线，不能以数字开头");
        }
        while(!checkPwd(password)) {
            throw new RuntimeException("密码:必须是6-20位的字母、数字、下划线");
        }
        User userDB = userService.findByUsername(username);
        if (null != userDB){
            throw new RuntimeException("用户名已经存在");
        }
        String MD5PWD = new Md5Hash(password,username).toString();
        user.setPassword(MD5PWD);
        user.setLastLoginTime(LocalDateTime.now());
        userService.add(user);
        return new Result(true, StatusCode.OK,"添加成功");
    }

    /**
     * 2标记离职
     * @param data
     * @return
     */
    // @RequiresPermissions("user:delete")
    @PostMapping("/delete")
    public Result delete(@RequestBody String data){
        log.info("标记离职");
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        User byId = userService.findById(id);
        byId.setDeleted(1);
        userService.update(byId);
        return new Result(true, StatusCode.OK,"标记离职");
    }
    @PostMapping("/deleteReal")
    public Result deleteReal(@RequestBody String data){
        log.info("彻底物理删除员工");
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSON.parseObject(data);
        String userIdStr = jsonObject.getString("userId");
        Integer userId = Integer.valueOf(userIdStr);
        User byId = userService.findById(userId);
        byId.setDeleted(1);
        userService.update(byId);
        return new Result(true, StatusCode.OK,"标记离职");
    }

    /**
     * 3更新角色
     * @param data
     * @return
     */
    //@RequiresPermissions("user:update")
    @PostMapping(value="/update")
    public Result update(@RequestBody String data){
        log.info("更新角色"+data);
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer userId = jsonObject.getInteger("userId");
        Integer roleId = jsonObject.getInteger("roleId");
        log.info("userId>>>"+ userId+ ":::roleId>>>" +roleId);
        User user = userService.findById(userId);
        if (null==user){return  new Result(false, StatusCode.ERROR,"找不到用户");}
        user.setRoleId(roleId);
        log.info("用户:"+ user.getName()+":的角色变更>>" +roleId);
        userService.update(user);
        return new Result(true, StatusCode.OK,"更新角色成功");
    }
    public UserVO user2vo(User user){
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        Role role = roleService.findById(user.getRoleId());
        userVO.setRoleName(role.getRoleName());
        return  userVO;
    }

    @PostMapping("/search")
    public Result findList(@RequestBody String data){
        log.info("searchMap>>>>>" + data );
        JSONObject jsonObject = JSON.parseObject(data);
        String userStr = jsonObject.getString("data");
        Map map = JSON.parseObject(userStr);
        System.out.println("map>>" +map);
        Integer deleted = (Integer)map.get("deleted");
        if (null == deleted){  map.put("deleted",0);}
        Integer page = jsonObject.getInteger("page");
        if (null ==page) {page=1;}
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (null ==pageSize) {pageSize = 10;}

        Page<User> pageResult = userService.findList(map,page,pageSize);
        List<UserVO> userVOList=new ArrayList<>();
        for (User user : pageResult) {
            UserVO userVO = user2vo(user);
            userVOList.add(userVO);
        }

        PageResult<UserVO> userVOPageResult = new PageResult<>((long) userVOList.size(), userVOList);
        return new Result<>(true, StatusCode.OK,"查询用户成功",userVOPageResult);
    }

    @PostMapping("/info")
    public Result findSigle(@RequestBody String data){
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        User byId = userService.findById(id);
        UserVO userVO = user2vo(byId);
        System.out.println(userVO);
        return new Result(true, StatusCode.OK,"查询员工成功",userVO);
    }
}

